import itchat
from itchat.content import *
from urllib import request
import json

print_switch = True

user_list = ["倪永贵"]

def check_user(user):
    print(user.get("RemarkName"))
    if user_list.count(user.get("RemarkName"))>0:return True
    return False

# def get_reply():
#     url = "http://www.tuling123.com/openapi/api"
#     key = "24f6698d5c9346f4989f906ab74a1e8d"
#     info = msg["Text"].encode("utf-8")
#     from_user = msg["FromUserName"]
#     userid = from_user[1:]
#     url += "?key={key}&info={info}&userid={userid}".format(key=key, info=info, userid=userid)
#     if print_switch: print(url)
#     res = request.urlopen(url)
#     # print(str(res.read(),encoding="utf-8"))
#     s = json.load(res, encoding="utf-8")

@itchat.msg_register([TEXT])
def text_reply(msg):
    if print_switch:print(msg)
    if check_user(msg["User"]):
        url = "http://www.tuling123.com/openapi/api"
        key = "2adb2c87ad7b4fbb858b4cefb1a83763"
        info = msg["Text"].encode("utf-8")
        from_user = msg["FromUserName"]
        userid = from_user[1:]
        url += "?key={key}&info={info}&userid={userid}".format(key=key,info=info,userid=userid)
        if print_switch:print(url)
        res = request.urlopen(url)
        # print(str(res.read(),encoding="utf-8"))
        s = json.load(res,encoding="utf-8")
        if print_switch:print(s)
        if s["code"]==100000:
            if from_user!="@b286532c8f4d7cc7408368bf5c91b328" or from_user != "":
                itchat.send(s["text"],from_user)

itchat.auto_login(enableCmdQR=False,hotReload=True)
itchat.run(debug=True)